// 避免使用桶文件
// utils/index.ts
// https://vueuse.org/
export { useScroll } from "./useScroll";
export { useLazy } from "./useLazy";
export { useCache, saveStore, getStore } from "./useCache";
export { useResize } from "./useResize";
export { useDrag } from "./useDrag";
export { useBase64 } from "./useBase64";
export { useFile } from "./useFile";

/**
 * 防抖
 * 多用于点击事件
 * tips:
 * 1. 定时器是通过调用 setTimeout() 或 setInterval() 方法创建的
 * 一旦定时器被创建，它就会在指定的时间间隔后触发相应的回调函数，并且无法自动取消。
 * 因此，即使将 timer 设置为 null，原先设定的定时器仍然会执行，
 * 除非使用 clearTimeout() 或 clearInterval() 显式地取消定时器。
 * 2. clearTimeout 接受一个参数，这个参数是 setTimeout 返回的定时器 ID，它是一个数字。
 */
export const debounce = (
  func: Function,
  wait: number,
  immediate: boolean = false
) => {
  let timer: any = null;
  if (immediate) {
    // 前缘防抖
    return function (...args: any[]) {
      if (timer === null) {
        func.apply(this, args);
      }
      clearTimeout(timer);
      timer = setTimeout(() => {
        clearTimeout(timer);
        timer = null;
      }, wait);
    };
  } else {
    // 防抖
    return function (...args: any[]) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(this, args);
        clearTimeout(timer);
        timer = null;
      }, wait);
    };
  }
};

/**
 * 节流
 * 多用于滚动条、拖拽
 */
export const throttle = (
  func: Function,
  wait: number,
  immediate: boolean = false
) => {
  let timer: number | null = null;
  if (immediate) {
    // 前缘节流
    return function (...args: any[]) {
      if (timer === null) {
        func.apply(this, args);
        timer = setTimeout(() => {
          clearTimeout(timer as number);
          timer = null;
        }, wait) as unknown as number;
      }
    };
  } else {
    return function (...args: any[]) {
      if (timer === null) {
        timer = setTimeout(() => {
          func.apply(this, args);
          clearTimeout(timer as number);
          timer = null;
        }, wait) as unknown as number;
      }
    };
  }
};

export const isObject = (obj: any) => {
  return Object.prototype.toString.call(obj) === "[object Object]";
};
